﻿// Copyright © Microsoft Corporation.  All Rights Reserved.
// This code released under the terms of the 
// Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)

using System;
using System.Diagnostics;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using AdminApp.Controls;
using AdminApp.Resources;
using AdminApp.Web;
using AdminApp.Web.Services;

namespace AdminApp.Views
{
    public partial class Slots : Page
    {
        public Slots()
        {
            InitializeComponent();
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void eventDomainDataSource_LoadedData(object sender, LoadedDataEventArgs e)
        {
            if (e.HasError)
            {
                System.Windows.MessageBox.Show(e.Error.ToString(), "Load Error", System.Windows.MessageBoxButton.OK);
                e.MarkErrorAsHandled();
            }
            _eventCombo.SelectedIndex = -1;
        }

        private void roomDomainDataSource_LoadedData(object sender, LoadedDataEventArgs e)
        {
            if (e.HasError)
            {
                System.Windows.MessageBox.Show(e.Error.ToString(), "Load Error", System.Windows.MessageBoxButton.OK);
                e.MarkErrorAsHandled();
            }
            RoomConverter sc = this.Resources["RoomConverter1"] as RoomConverter;
            if (sc != null)
            {
                sc.RoomData = roomDomainDataSource.DomainContext as DigitalSignageDomainContext;
            }
        }

        private void slotDomainDataSource_LoadedData(object sender, LoadedDataEventArgs e)
        {
            if (e.HasError)
            {
                System.Windows.MessageBox.Show(e.Error.ToString(), "Load Error", System.Windows.MessageBoxButton.OK);
                e.MarkErrorAsHandled();
            }
        }

        private void sessionDomainDataSource_LoadedData(object sender, LoadedDataEventArgs e)
        {
            if (e.HasError)
            {
                System.Windows.MessageBox.Show(e.Error.ToString(), "Load Error", System.Windows.MessageBoxButton.OK);
                e.MarkErrorAsHandled();
            }

            SessionConverter sc = this.Resources["SessionConverter1"] as SessionConverter;
            if (sc != null)
            {
                sc.SessionData = sessionDomainDataSource.DomainContext as DigitalSignageDomainContext;
            }
        }

        private void speakerDomainDataSource_LoadedData(object sender, LoadedDataEventArgs e)
        {
            if (e.HasError)
            {
                System.Windows.MessageBox.Show(e.Error.ToString(), "Load Error", System.Windows.MessageBoxButton.OK);
                e.MarkErrorAsHandled();
            }

            SpeakerConverter sc = this.Resources["SpeakerConverter1"] as SpeakerConverter;
            if (sc != null)
            {
                sc.SpeakerData = speakerDomainDataSource.DomainContext as DigitalSignageDomainContext;
            }

            SpeakerIdImageConverter si = this.Resources["SpeakerImageConverter1"] as SpeakerIdImageConverter;
            if (si != null)
            {
                si.SpeakerData = speakerDomainDataSource.DomainContext as DigitalSignageDomainContext;
            }

            
        }

        //DateTime _lastDateTime;

        #region Button - Events

        //private void _save_Click(object sender, RoutedEventArgs e)
        //{
        //    _lastDateTime = ((AllDatesByRoom)_dayCombo.SelectedItem).Date;
        //    slotDomainDataSource.SubmitChanges();
        //}

        //private void _reject_Click(object sender, RoutedEventArgs e)
        //{
        //    slotDomainDataSource.RejectChanges();
        //}

        private void _add_Click(object sender, RoutedEventArgs e)
        {
            //_lastDateTime = ((AllDatesByRoom)_dayCombo.SelectedItem).Date;
            AddSlot();
        }

        private void _remove_Click(object sender, RoutedEventArgs e)
        {
            if (_slotList.SelectedItem != null)
            {
                QuestionWindow qw = 
                    new QuestionWindow(ApplicationStrings.DeleteSlotQuestion, DeleteSlot);
                qw.Show();
            }
        }

        #endregion

        private void AddSlot()
        {
            Web.Slot slot = new Web.Slot();
            slot.Date = DateTime.Today;
            slot.Time = new TimeSpan(9, 0, 0);
            slot.RoomId = ((Web.Room)_selectRoomCombo.SelectedItem).Id;

            DigitalSignageDomainContext context =
                slotDomainDataSource.DomainContext as DigitalSignageDomainContext;

            context.Slots.Add(slot);
            _slotList.DataContext = context;
        }

        private void DeleteSlot()
        {
            Web.Slot slot = _slotList.SelectedItem as Web.Slot;
            DigitalSignageDomainContext context =
                slotDomainDataSource.DomainContext as DigitalSignageDomainContext;

            context.Slots.Remove(slot);
            _slotList.DataContext = context;
        }

        private void allDatesByRoomDomainDataSource_LoadedData(object sender, LoadedDataEventArgs e)
        {
            if (e.HasError)
            {
                System.Windows.MessageBox.Show(e.Error.ToString(), "Load Error", System.Windows.MessageBoxButton.OK);
                e.MarkErrorAsHandled();
            }
            else
            {
                // Select last selected day
                //if (_lastDateTime != new DateTime())
                //{
                //    foreach (var ci in _dayCombo.Items)
                //    {
                //        AllDatesByRoom help = ci as AllDatesByRoom;
                //        if (help.Date == _lastDateTime)
                //        {
                //            _dayCombo.SelectedItem = help;
                //            return;
                //        }
                //    }
                //}
            }
        }

        private void _eventCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            LoadRooms();
        }

        private void _roomCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            LoadDates();
        }
        
        private void _dayCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            LoadSlots();
        }
       
        private void LoadRooms()
        {
            roomDomainDataSource.DomainContext.EntityContainer.Clear();

            Web.Event ev = _eventCombo.SelectedItem as Web.Event;

            if (ev != null)
            {
                roomDomainDataSource.QueryParameters.Clear();
                System.Windows.Data.Parameter param = new System.Windows.Data.Parameter();
                param.ParameterName = "eventId";
                param.Value = ev.Id;
                roomDomainDataSource.QueryParameters.Add(param);
                roomDomainDataSource.Load();
            }
        }

        private void LoadDates()
        {
            Web.Room room = _selectRoomCombo.SelectedItem as Web.Room;

            if (room != null)
            {
                allDatesByRoomDomainDataSource.QueryParameters.Clear();

                // Room
                System.Windows.Data.Parameter param = new System.Windows.Data.Parameter();
                param.ParameterName = "roomId";
                param.Value = room.Id;
                allDatesByRoomDomainDataSource.QueryParameters.Add(param);

                allDatesByRoomDomainDataSource.Load();
            }
        }

        private void LoadSlots()
        {
            Web.Room room = _selectRoomCombo.SelectedItem as Web.Room;

            AllDatesByRoom date = _dayCombo.SelectedItem as Web.AllDatesByRoom;

            if (room != null && date != null)
            {
                if (slotDomainDataSource.IsLoadingData)
                {
                    slotDomainDataSource.CancelLoad();
                }
                slotDomainDataSource.DomainContext.EntityContainer.Clear();
                slotDomainDataSource.QueryParameters.Clear();
                
                // Room
                System.Windows.Data.Parameter param = new System.Windows.Data.Parameter();
                param.ParameterName = "roomId";
                param.Value = room.Id;
                slotDomainDataSource.QueryParameters.Add(param);

                // Date
                param = new System.Windows.Data.Parameter();
                param.ParameterName = "date";
                param.Value = ((Web.AllDatesByRoom)(_dayCombo.SelectedItem)).Date;
                slotDomainDataSource.QueryParameters.Add(param);

                slotDomainDataSource.Load();
            }
        }

        private void slotDomainDataSource_SubmittedChanges(object sender, SubmittedChangesEventArgs e)
        {
            LoadDates();
        }

        private void ComboBox_BindingValidationError(object sender, ValidationErrorEventArgs e)
        {
            Debug.WriteLine(e.Error.Exception.Message);
        }

        private void roomDomainDataSource1_LoadedData(object sender, LoadedDataEventArgs e)
        {

            if (e.HasError)
            {
                System.Windows.MessageBox.Show(e.Error.ToString(), "Load Error", System.Windows.MessageBoxButton.OK);
                e.MarkErrorAsHandled();
            }
        }

        private void _roomIdCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ComboBox cb = sender as ComboBox;
            Web.Slot slot = _slotList.SelectedItem as Web.Slot;

            if (slot != null)
            {
                Web.Room room = cb.SelectedItem as Web.Room;
                if (room == null)
                {
                    slot.RoomId = null;
                }
                else
                {
                    slot.RoomId = room.Id;
                }
            }
        }

        private void _sessionIdCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ComboBox cb = sender as ComboBox;
            Web.Slot slot = _slotList.SelectedItem as Web.Slot;

            if (slot != null)
            {
                Web.Session session = cb.SelectedItem as Web.Session;
                if (session == null)
                {
                    slot.SessionId = null;
                }
                else
                {
                    slot.SessionId = session.Id;
                }
            }
        }

        private void _speakerIdCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ComboBox cb = sender as ComboBox;
            Web.Slot slot = _slotList.SelectedItem as Web.Slot;

            if (slot != null)
            {
                Web.Speaker speaker = cb.SelectedItem as Web.Speaker;
                if (speaker != null)
                {
                    slot.SpeakerId = speaker.Id;
                }
                else
                {
                    slot.SpeakerId = null;
                }
            }
        }


        private void _slotList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            _roomIdCombo.SelectionChanged -= _roomIdCombo_SelectionChanged;
            _sessionIdCombo.SelectionChanged -= _sessionIdCombo_SelectionChanged;
            _speakerIdCombo.SelectionChanged -= _speakerIdCombo_SelectionChanged;
            
            UpdateCombos();
            _roomIdCombo.SelectionChanged += _roomIdCombo_SelectionChanged;
            _sessionIdCombo.SelectionChanged += _sessionIdCombo_SelectionChanged;
            _speakerIdCombo.SelectionChanged += _speakerIdCombo_SelectionChanged;
        }

        private void UpdateCombos()
        {
            Web.Slot slot = _slotList.SelectedItem as Slot;

            if (slot == null)
            {
                // Rooom 
                _roomIdCombo.SelectedItem = null;

                // Session
                _sessionIdCombo.SelectedItem = null;

                // Speaker 1
                _speakerIdCombo.SelectedItem = null;
            }
            else
            {
                // Rooom 
                foreach (var room in _roomIdCombo.Items.OfType<Web.Room>())
                {
                    if (room.Id.Equals(slot.RoomId))
                    {
                        _roomIdCombo.SelectedItem = room;
                        break;
                    }
                    _roomIdCombo.SelectedItem = null;
                }

                // Session
                _sessionIdCombo.SelectedItem = null;
                foreach (var session in _sessionIdCombo.Items.OfType<Web.Session>())
                {
                    if (session.Id.Equals(slot.SessionId))
                    {
                        _sessionIdCombo.SelectedItem = session;
                        break;
                    }
                    _sessionIdCombo.SelectedItem = null;
                }

                // Speaker 1
                _speakerIdCombo.SelectedItem = null;
                foreach (var speaker in _speakerIdCombo.Items.OfType<Web.Speaker>())
                {
                    if (speaker.Id.Equals(slot.SpeakerId))
                    {
                        _speakerIdCombo.SelectedItem = speaker;
                        break;
                    }
                    _speakerIdCombo.SelectedItem = null;
                }

            }
        }

        private void _clearRoom1_Click(object sender, RoutedEventArgs e)
        {
            _roomIdCombo.SelectedItem = null;
        }

        private void _clearSession_Click(object sender, RoutedEventArgs e)
        {
            _sessionIdCombo.SelectedItem = null;
        }

        private void _clearSpeaker1_Click(object sender, RoutedEventArgs e)
        {
            _speakerIdCombo.SelectedItem = null;
        }

    }
}
